%% @author Administrator
%% @doc @todo Add description to utils.


-module(utils).

-include("tcp.hrl").
-include("usr.hrl").

%% ====================================================================
%% API functions
%% ====================================================================
-compile(export_all).
%-export([]).
%% ====================================================================
%% Internal functions 
%% ====================================================================
skip_blanks_zero([$\s|T]) ->
	skip_blanks_zero(T);
skip_blanks_zero([0|T]) ->
	skip_blanks_zero(T);
skip_blanks_zero(X) ->X.

trimblanks(X) ->
	lists:reverse(skip_blanks_zero( lists:reverse(X))).
trim(Bin) ->
	list_to_binary(trimblanks(binary_to_list(Bin)) ).

getsockfromname(User)->
	NameTo = utils:trim(User),
	io:format("Msg to:~p~n",[NameTo]),
	ToSock = case ets:lookup(socksession,NameTo) of
		[]->
			[];
		[Rec]->
			Rec#socksession.sock
		end.


readconf() ->
	case file:consult("settings.conf") of
	{ok,ArgList} ->
		io:format("~p~n",[ArgList]),
		parseArg(ArgList),
		ok;
	_Any->
		ok
	end.
parseArg([])->
	ok;
parseArg([H|T])->
	case H of
	 {logsave,Op}->
		
		LS = #logsave{op=Op},
		io:format("logsave ~p~n",[LS]),
		ets:insert(logsave,LS),
		parseArg(T);
	 {logpath,Name,Mode}->
		ets:insert(logpath,H),
		IsSave = is_log2_file(),
		io:format("Is Save? ~p~n",[IsSave]),
		if
		 IsSave =:= true->
		     {ok,Device} = file:open(Name,Mode),
		     LD = #logfile{device = Device},
		     ets:insert(logfile,LD);
		  true->
			ok
		 end,
		parseArg(T);
	 _Any->
		parseArg(T)
	end.
is_log2_file()->
	Key = ets:first(logsave),
	%io:format("Key = ~p~n",[Key]),
	case ets:lookup(logsave,Key) of
	     []->
		false;
	     [Rec]->
		Rec#logsave.op
	end.
send(Sock,Data) ->
	if 
	is_port(Sock) =:= true->
	case gen_tcp:send( Sock, Data) of
	 ok ->
	     ok;
	 {error,Reason}->
	     log:log_out("SOCKET send error:~p~nThese data is not sent:~n~p~n",[Reason,Data]),
	     error
	end;
	true->
	  log:log_out("Can not send, because no socket is specified, or the socket is not safe~n")
	end.